package com.sc.nft.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.nft.dao.IdcardInfoDao;
import com.sc.nft.dao.MallActivityRankingCyclesDao;
import com.sc.nft.dao.MallActivityRankingDao;
import com.sc.nft.dao.MallUserActivityRankingDetailDao;
import com.sc.nft.dao.UserInfoDao;
import com.sc.nft.entity.IdcardInfo;
import com.sc.nft.entity.MallActivityRanking;
import com.sc.nft.entity.MallActivityRankingCycles;
import com.sc.nft.entity.MallUserActivityRankingDetail;
import com.sc.nft.entity.UserInfo;
import com.sc.nft.entity.dto.MallUserActivityRankingDetailDTO;
import com.sc.nft.entity.vo.MallUserActivityRankingDetailVO;
import com.sc.nft.pool.UserPool;
import com.sc.nft.service.MallUserActivityRankingDetailService;
import com.sc.nft.util.PhoneUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 用户排行榜
 *
 * @author zxy
 * @description IP商城
 * @since 2023-05-10 16:59:01
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class MallUserActivityRankingDetailServiceImpl implements MallUserActivityRankingDetailService {

    private final MallUserActivityRankingDetailDao mallUserActivityRankingDetailDao;

    private final MallActivityRankingDao mallActivityRankingDao;

    private final MallActivityRankingCyclesDao mallActivityRankingCyclesDao;

    private final IdcardInfoDao idcardInfoDao;

    private final UserInfoDao userInfoDao;


    /**
     * 查询排行榜（B端）
     *
     * @param cyclesId
     * @return
     */
    @Override
    public IPage<MallUserActivityRankingDetailDTO> queryMallUserActivityRankingDetailPage(Page toMp, Long cyclesId, String phoneNumber) {
        MallActivityRankingCycles mallActivityRankingCycles = mallActivityRankingCyclesDao.getById(cyclesId);
        MallActivityRanking mallActivityRanking = mallActivityRankingDao.getById(mallActivityRankingCycles.getRankingId());

        IPage mallUserActivityRankingDetailList = mallUserActivityRankingDetailDao.queryUserRankingPage(toMp,cyclesId, mallActivityRanking.getNumOfUsers(),phoneNumber,mallActivityRanking.getThresholdAmount());
        List<MallUserActivityRankingDetail> records = mallUserActivityRankingDetailList.getRecords();
        List<MallUserActivityRankingDetailDTO> mallUserActivityRankingDetailDTOList = new ArrayList<>();
        for (MallUserActivityRankingDetail mallUserActivityRankingDetail : records) {
            MallUserActivityRankingDetailDTO mallUserActivityRankingDetailDTO = new MallUserActivityRankingDetailDTO();
            mallUserActivityRankingDetailDTO.setRanking(mallUserActivityRankingDetail.getRanking());
            mallUserActivityRankingDetailDTO.setRankingCycleId(mallUserActivityRankingDetail.getRankingCycleId());
            mallUserActivityRankingDetailDTO.setTotalAmount(mallUserActivityRankingDetail.getTotalAmount());
            mallUserActivityRankingDetailDTO.setPhoneNumber(mallUserActivityRankingDetail.getPhoneNumber());
            mallUserActivityRankingDetailDTO.setConfirmedTotalAmount(mallUserActivityRankingDetail.getConfirmedTotalAmount());
            mallUserActivityRankingDetailDTO.setNickName(mallUserActivityRankingDetail.getNickname());
            mallUserActivityRankingDetailDTO.setIdCard(mallUserActivityRankingDetail.getIdCard());
            mallUserActivityRankingDetailDTOList.add(mallUserActivityRankingDetailDTO);
        }
        mallUserActivityRankingDetailList.setRecords(mallUserActivityRankingDetailDTOList);
        return mallUserActivityRankingDetailList;
    }

    /**
     * 查询排行榜（C端）
     *
     * @param cyclesId
     * @return
     */
    @Override
    public MallUserActivityRankingDetailVO queryMallUserActivityRankingDetailList(Long cyclesId) {
        UserInfo user = UserPool.getUser();

        MallUserActivityRankingDetailVO mallUserActivityRankingDetailVO = new MallUserActivityRankingDetailVO();
        mallUserActivityRankingDetailVO.setAvatarImg(user.getAvatarImg());
        if(cyclesId == null){
            return mallUserActivityRankingDetailVO;
        }
        MallActivityRankingCycles mallActivityRankingCycles = mallActivityRankingCyclesDao.getById(cyclesId);
        MallActivityRanking mallActivityRanking = mallActivityRankingDao.getById(mallActivityRankingCycles.getRankingId());
        List<MallUserActivityRankingDetail> mallUserActivityRankingDetailList = mallUserActivityRankingDetailDao.getUserRanking(cyclesId, mallActivityRanking.getNumOfUsers(), mallActivityRankingCycles.getThresholdAmount());
        List<MallUserActivityRankingDetailDTO> mallUserActivityRankingDetailDTOList = new ArrayList<>();
        Integer ranking = 1;
        for (MallUserActivityRankingDetail mallUserActivityRankingDetail : mallUserActivityRankingDetailList) {
            MallUserActivityRankingDetailDTO mallUserActivityRankingDetailDTO = new MallUserActivityRankingDetailDTO();
            mallUserActivityRankingDetailDTO.setRanking(ranking);
            mallUserActivityRankingDetailDTO.setRankingCycleId(mallUserActivityRankingDetail.getRankingCycleId());
            mallUserActivityRankingDetailDTO.setTotalAmount(mallUserActivityRankingDetail.getTotalAmount());
            mallUserActivityRankingDetailDTO.setPhoneNumber(PhoneUtils.maskPhoneNumber(mallUserActivityRankingDetail.getPhoneNumber()));
            mallUserActivityRankingDetailDTO.setConfirmedTotalAmount(mallUserActivityRankingDetail.getConfirmedTotalAmount());
            mallUserActivityRankingDetailDTOList.add(mallUserActivityRankingDetailDTO);

            if (mallUserActivityRankingDetail.getUserId().equals(user.getId())) {
                mallUserActivityRankingDetailVO.setRanking(ranking);
            }
            ranking++;
        }
        MallUserActivityRankingDetail mallUserActivityRankingDetail = this.get(user.getId(),cyclesId);
        if(mallUserActivityRankingDetail != null){
            mallUserActivityRankingDetailVO.setConfirmedTotalAmount(mallUserActivityRankingDetail.getConfirmedTotalAmount());
            mallUserActivityRankingDetailVO.setTotalAmount(mallUserActivityRankingDetail.getTotalAmount());
        }
        mallUserActivityRankingDetailVO.setAvatarImg(user.getAvatarImg());
        mallUserActivityRankingDetailVO.setMallUserActivityRankingDetailDTOList(mallUserActivityRankingDetailDTOList);
        mallUserActivityRankingDetailVO.setMallActivityRankingCycles(mallActivityRankingCycles);
        mallUserActivityRankingDetailVO.setActivityRules(mallActivityRanking.getActivityRules());
        return mallUserActivityRankingDetailVO;
    }


    @Override
    public Boolean saveOrUpdate(Long userId, BigDecimal confirmedTotalAmount, BigDecimal totalAmount, Date statisticTime) {
        UserInfo user = userInfoDao.getById(userId);
        //获取当前期数id
        MallActivityRanking mallActivityRanking = mallActivityRankingDao.getMallActivityRanking();
        if(mallActivityRanking == null){
            return true;
        }
        List<MallActivityRankingCycles> mallActivityRankingCyclesList = mallActivityRankingCyclesDao.queryMallActivityRankingCyclesList(mallActivityRanking.getId(),statisticTime);
        IdcardInfo idcardInfo = idcardInfoDao.findLastOneByUserIdAndIsPass(userId);
        for (MallActivityRankingCycles mallActivityRankingCycles : mallActivityRankingCyclesList) {
            Long cyclesId = mallActivityRankingCycles.getId();
            MallUserActivityRankingDetail mallUserActivityRankingDetailDO = this.get(userId, cyclesId);
            if (mallUserActivityRankingDetailDO != null) {
                if (confirmedTotalAmount != null) {
                    mallUserActivityRankingDetailDao.updateConfirmedTotalAmount(userId, cyclesId, confirmedTotalAmount);
                } else {
                    mallUserActivityRankingDetailDao.updateTotalAmount(userId, cyclesId, totalAmount);
                }
            } else {
                MallUserActivityRankingDetail mallUserActivityRankingDetail = new MallUserActivityRankingDetail();
                mallUserActivityRankingDetail.setUserId(userId);
                mallUserActivityRankingDetail.setNickname(user.getNickName());
                mallUserActivityRankingDetail.setIdCard(idcardInfo.getCardId());
                mallUserActivityRankingDetail.setPhoneNumber(user.getUserTel());
                mallUserActivityRankingDetail.setConfirmedTotalAmount(confirmedTotalAmount == null ? BigDecimal.ZERO : confirmedTotalAmount);
                mallUserActivityRankingDetail.setTotalAmount(totalAmount == null ? BigDecimal.ZERO : totalAmount);
                mallUserActivityRankingDetail.setRankingCycleId(mallActivityRankingCycles.getId());
                mallUserActivityRankingDetailDao.save(mallUserActivityRankingDetail);
            }
        }
        return true;
    }


    /**
     * 通过userId和周期id获取统计记录
     *
     * @param userId
     * @return
     */
    public MallUserActivityRankingDetail get(Long userId, Long rankingCycleId) {
        LambdaQueryWrapper<MallUserActivityRankingDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MallUserActivityRankingDetail::getUserId, userId);
        wrapper.eq(MallUserActivityRankingDetail::getRankingCycleId, rankingCycleId);
        wrapper.last("limit 1");
        return mallUserActivityRankingDetailDao.getOne(wrapper);
    }
}